package abrindoojogo.exemplos.thread;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
import javax.swing.WindowConstants;

public class JogoThread extends JFrame implements KeyListener
{
    BufferStrategy bs;
    Contador contador;
    Nave nave;

    public JogoThread()
    {
	setUndecorated(true);
	setSize(800, 600);
	Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
	setLocation(d.width / 2 - 400, d.height / 2 - 300);
	setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
	setIgnoreRepaint(true);
	addKeyListener(this);
	contador = new Contador();
	nave = new Nave();
    }

    public void gameloop()
    {
	initialize();
	Controlador c = new Controlador(this, contador, nave);
	Renderizador r = new Renderizador(this, bs, contador, nave);
	Thread t;
	t = new Thread(c);
	t.start();
	t = new Thread(r);
	t.start();
    }

    public void initialize()
    {
	setVisible(true);
	createBufferStrategy(2);
	bs = getBufferStrategy();

	nave.x = 400;
	nave.y = 50;
	nave.qtd = 1;

	contador.inicia();
    }

    public void keyPressed(KeyEvent e)
    {
	if (e.getKeyCode() == KeyEvent.VK_ESCAPE)
	{
	    System.out.println("Pulsos: " + contador.getPulsosPorSegundo() + "  Frames: " + contador.getFramesPorSegundo() + "          naves: " + nave.qtd);
	    System.exit(0);
	}

	if (e.getKeyCode() == KeyEvent.VK_UP)
	{
	    nave.y -= 1;
	}
	if (e.getKeyCode() == KeyEvent.VK_DOWN)
	{
	    nave.y += 1;
	}
	if (e.getKeyCode() == KeyEvent.VK_RIGHT)
	{
	    if (nave.qtd < 1054)
	    {
		nave.qtd += 1;
	    }
	}
	if (e.getKeyCode() == KeyEvent.VK_LEFT)
	{
	    if (nave.qtd > 1)
	    {
		nave.qtd -= 1;
	    }
	}
    }

    public void keyReleased(KeyEvent e)
    {
    }

    public void keyTyped(KeyEvent e)
    {
    }
}
